/**
 * React Hook for handling encrypted data fetching and decryption
 */

import { useState, useCallback } from 'react';
import { decryptAndParse } from '../utils/aesDecryptor';

/**
 * Custom hook for fetching and decrypting encrypted data
 * @param {Function} fetchFunction - Function that returns encrypted data
 * @returns {Object} Hook state and methods
 */
const useEncryptedData = (fetchFunction) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  /**
   * Fetch and decrypt data
   * @param {Object} options - Fetch options
   */
  const fetchData = useCallback(async (options = {}) => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetchFunction(options);
      
      if (response && typeof response === 'string') {
        // Data is encrypted, decrypt it
        try {
          const decryptedData = await decryptAndParse(response);
          setData(decryptedData);
        } catch (decryptError) {
          console.error('数据解密失败:', decryptError);
          setError('数据解密失败');
          // Fallback: try to use the data as-is
          try {
            const parsedData = JSON.parse(response);
            setData(parsedData);
          } catch (parseError) {
            setData(response);
          }
        }
      } else if (Array.isArray(response)) {
        // Data is already decrypted or not encrypted
        setData(response);
      } else {
        setData(response);
      }
    } catch (fetchError) {
      console.error('获取数据失败:', fetchError);
      setError('获取数据失败');
    } finally {
      setLoading(false);
    }
  }, [fetchFunction]);

  /**
   * Clear data and error state
   */
  const clearData = useCallback(() => {
    setData(null);
    setError(null);
  }, []);

  return {
    data,
    loading,
    error,
    fetchData,
    clearData,
    setData
  };
};

export default useEncryptedData;
